<template>
  <div>


    <el-select v-model="tableName" @change="changeTableName" filterable placeholder="表名">
      <el-option v-for="item in tableNames" :key="item.tableName" :label="item.tableName" :value="item.tableName"></el-option>
    </el-select>

    <el-button type="primary" icon="el-icon-plus" @click="add">新增列</el-button>
    <el-button type="danger" icon="el-icon-delete" @click="deleteAll">清空列</el-button>
    <el-button type="primary" icon="fa fa-rocket mr-8" @click="code">生成代码</el-button>
    <el-table
      :data="columnData"
      style="width: 100%">
      <el-table-column
        prop="columnName"
        label="列名"
        width="180">
      </el-table-column>
      <el-table-column
        prop="columnComment"
        label="列名备注">
      </el-table-column>
      <el-table-column
        prop="elementType"
        label="元素类型"
        width="180">
        <template slot-scope="scope">
          <es-value-format  :data="elementTypeData" :value="scope.row.elementType"></es-value-format>
        </template>
      </el-table-column>
      <el-table-column
        prop="dataSourceType"
        label="数据源类型">
        <template slot-scope="scope">
          <es-value-format  :data="dataSourceTypeData" :value="scope.row.dataSourceType"></es-value-format>
        </template>
      </el-table-column>
      <el-table-column
        prop="dataSource"
        label="数据源">
        <template slot-scope="scope">
          <span>{{scope.row.dataSource||'-'}}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="maxLength"
        label="长度">
        <template slot-scope="scope">
          <span>{{scope.row.maxLength||'-'}}</span>
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        label="操作"
        show-overflow-tooltip
        width="220">
        <template slot-scope="scope">
          <el-button
            size="mini" type="primary"
            @click="handleEdit(scope.$index,scope.row)">编辑
          </el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--新增修改-->
    <el-dialog :title="title" :visible="action==='add' || action==='edit'" :before-close="handleClose">
      <el-form :model="item" :rules="rules" ref="ruleForm" label-width="100px">
        <div class="form-item-group">
          <el-form-item label="列名" prop="columnName">
            <el-input v-model="item.columnName"
                      placeholder="请输入列名"
                      maxlength="50"
                      show-word-limit
            ></el-input>
          </el-form-item>

          <el-form-item label="列名备注" prop="columnComment">
            <el-input v-model="item.columnComment"
                      placeholder="请输入列名备注"
                      maxlength="50"
                      show-word-limit
            ></el-input>
          </el-form-item>

          <el-form-item label="元素类型" prop="elementType">
            <es-select
              v-model="item.elementType"
              :data="elementTypeData"
              show-tip
              tip-text="请选择元素类型"
            ></es-select>
          </el-form-item>

          <el-form-item label="长度" prop="maxLength" v-if="item.elementType && item.elementType === 'input' && item.elementType !== 'uploadImg'">
            <el-input v-model="item.maxLength"
                      placeholder="请输入长度"
            ></el-input>
          </el-form-item>

          <el-form-item label="数据源类型" prop="dataSourceType" v-if="item.elementType && item.elementType !== 'input'  && item.elementType !== 'uploadImg'">
            <es-select
              v-model="item.dataSourceType"
              :data="dataSourceTypeData"
              @change="changeDataSourceType"
              show-tip
              tip-text="请选择数据源类型"
            ></es-select>
          </el-form-item>

          <el-form-item label="数据源" prop="dataSource" v-if="item.dataSourceType === 'url' && item.elementType !== 'input'  && item.elementType !== 'uploadImg'">
            <el-input
              v-model="item.dataSource"
                      placeholder="请输入数据源"
                      maxlength="50"
                      show-word-limit
            ></el-input>
          </el-form-item>

          <el-form-item label="数据源" prop="dataSource" v-if="item.dataSourceType === 'dict-name' && item.elementType !== 'input'  && item.elementType !== 'uploadImg'">
            <!--字典下拉-->
            <es-select
              :key="item.dataSourceType"
              v-model="item.dataSource"
              :data="dictNameData"
            ></es-select>
          </el-form-item>

          <el-form-item label="数据源" prop="dataSource" v-if="item.dataSourceType === 'enum-name' && item.elementType !== 'input'  && item.elementType !== 'uploadImg'">
            <!--枚举下拉-->
            <es-select
              :key="item.dataSourceType"
              v-model="item.dataSource"
              :data="enumNameData"
              show-tip
              tip-text="请选择枚举"
            ></es-select>
          </el-form-item>


        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="action = 'list'">取 消</el-button>
        <el-button type="primary" @click="saveColumn">确 定</el-button>
      </div>
    </el-dialog>

    <!--代码-->
    <el-dialog
      title="代码"
      :visible.sync="codeVisible"
      :before-close="handleClose">
        <code-preview :column-data="columnData" :code-html="codeHtml" :uuid="uuid"></code-preview>
    </el-dialog>
  </div>
</template>

<script>
  import {getColumns, selectTables} from '../../api/sys/generatorApi'
  import {getDataByUrl} from '../../api/getComData'
  import validate from '../../libs/validate'
  import CodePreview from '../../components/module/code-preview'
  export default {
    name: 'genForm',
    components: {CodePreview},
    data () {
      return {
        tableName: '',
        title: '',
        action: '',
        item: {},
        tableNames: [],
        columnData: [],
        codeVisible: false,
        codeHtml:[],//生成的代码
        uuid:'',//用于组件重新渲染
        elementTypeData:[],
        dataSourceTypeData:[],
        dataSourceData:[],
        dictNameData:[],
        enumNameData:[],
        rules: {  //表单验证
          columnName: [
            {required: true, message: '请输入列名', trigger: 'blur'}
          ],
          columnComment: [
            {required: true, message: '请输入列名备注', trigger: 'blur'}
          ],
          elementType: [
            {required: true, message: '请选择元素类型', trigger: 'blur'}
          ],
          dataSourceType: [
            {required: true, message: '请选择数据源类型', trigger: 'blur'}
          ],
          dataSource: [
            {required: true, message: '请输入数据源', trigger: 'blur'},
          ],
          maxLength: [
            {required: true, message: '请输入长度', trigger: 'blur'},
            {validator: validate.integer, trigger: 'blur'}
          ]
        }
      }
    },
    mounted () {
      let _this = this
      //获取表数据
      selectTables().then(res => {
        _this.tableNames = res.data
      })
      //获取表字段
      const tableName = this.$t.getUrlParams('tableName')
      if (tableName) {
        this.getColumns(tableName)
      }
      //获取元素类型
      getDataByUrl("/static/json/elementType.json", {}).then((res) => {
         if(res.code === 200){
           _this.elementTypeData=res.data;
         }
      })
      //获取数据源类型
      getDataByUrl("/static/json/dataSourceType.json", {}).then((res) => {
        if(res.code === 200){
          _this.dataSourceTypeData=res.data;
        }
      })
      //获取枚举列表
      getDataByUrl("/api/common/getEnumNames", {}).then((res) => {
        if(res.code === 200){
          _this.enumNameData=res.data;
        }
      })
      //获取字典列表
      getDataByUrl("/api/dict/getDictNames", {}).then((res) => {
        if(res.code === 200){
          _this.dictNameData=res.data;
        }
      })
    },
    methods: {
      code () {
        let _this =this;
        let codeTemplate = []
        let columnData = this.columnData
        for (let i = 0, len = columnData.length; i < len; i++) {
          //文本框
          if (columnData[i].elementType === 'input') {
            codeTemplate.push(`<el-input v-model="item.${columnData[i].columnName}" placeholder="请输入${columnData[i].columnComment}"  maxlength="${columnData[i].maxLength || 255}"  show-word-limit ></el-input>`)
          }
          //下拉框
          else if (columnData[i].elementType === 'select') {
            codeTemplate.push(`<es-select
                                    v-model="item.${columnData[i].columnName}"
                                    ${columnData[i].dataSourceType}="${columnData[i].dataSource}"
                                    show-tip
                                    tip-text="请选择${columnData[i].columnComment}"
                              > </es-select>`)
          }
          //复选框
          else if (columnData[i].elementType === 'checkbox') {
            codeTemplate.push(`<es-checkbox
                                    v-model="item.${columnData[i].columnName}"
                                    ${columnData[i].dataSourceType}="${columnData[i].dataSource}"
                              > </es-checkbox>`)
          }
          //下拉树
          else if (columnData[i].elementType === 'tree' && columnData[i].dataSourceType==='url') {
            codeTemplate.push(`<es-tree
                                    v-model="item.${columnData[i].columnName}"
                                    url="${columnData[i].dataSource}"
                     ;         > </es-tree>`)
          }
          //级联选择器
          else if (columnData[i].elementType === 'cascader' && columnData[i].dataSourceType==='url') {
            codeTemplate.push(`<es-cascader
                                    v-model="item.${columnData[i].columnName}"
                                    url="${columnData[i].dataSource}"
                     ;         > </es-cascader>`)
          }
          //图片上传
          else if (columnData[i].elementType === 'uploadImg' ) {
            codeTemplate.push(`<es-upload-img
                                    :value="item.${columnData[i].columnName}"
                                    @uploadSuccess="uploadSuccess"
                     ;         > </es-upload-img>`)
          }

        }
        _this.codeHtml = codeTemplate;
        _this.codeVisible = true;
      },
      //获取表字段
      getColumns (tableName) {
        let _this = this
        getColumns({tableName: tableName}).then(res => {
          _this.tableName = tableName
          _this.columnData = res.data
        })
      },
      changeDataSourceType(val,oldVal){
         if(oldVal !== this.item.dataSourceType){
           let item = Object.assign({},this.item);
           item.dataSource="";
           this.item = item;
         }
      },
      changeTableName (tableName) {
        this.getColumns(tableName)
      },
      saveColumn () {
        let _this = this
        _this.$refs['ruleForm'].validate(function (valid) {
          if (valid) {
            //保存
            if (_this.action === 'add') {
              _this.item.key=_this.item.dataSource;
              _this.columnData.push(_this.item)
              _this.$message.success('新增成功！')

            }
            //修改
            else if (_this.action === 'edit') {
              _this.$set(_this.columnData,_this.item.index,_this.item);
              _this.uuid=_this.$t.getUUID(16,16);
              _this.$message.success('修改成功！');
            }
            _this.action = 'list'
          }
        })
      },
      add () {
        this.item = {}
        this.action = 'add'
        this.title = '新增列'
      },
      handleEdit (index, row) {
        let item = Object.assign({},row);
        item.index=index;
        this.item = item;
        this.title = '修改列'
        this.action = 'edit'
      },
      handleDelete (index, row) {
        let _this = this
        _this.$confirm('确定删除当前列?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          callback: function (action, instance) {
            if (action === 'confirm') {
              _this.columnData.splice(index, 1)
              _this.$message.success('删除成功！')
            }
          }
        })
      },
      deleteAll () {
        let _this = this
        _this.$confirm('确定清空当前缓存的列?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          callback: function (action, instance) {
            if (action === 'confirm') {
              _this.columnData = []
              _this.$message.success('清空成功！')
            }
          }
        })
      },
      handleClose (done) {
        this.action = 'list'
        done()
      }
    }
  }
</script>


